/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * GUI.java
 *
 * Created on Dec 3, 2011, 9:05:06 AM
 */
package projectmangement;

import java.awt.event.FocusEvent;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;

/**
 *
 * @author trungquy
 */
public final class GUI extends javax.swing.JFrame {
    
    /** Creates new form GUI */
    public GUI() {
        initComponents();
        initTree();
        setLocationRelativeTo(null); // set frame display at center of screen
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jSplitPaneFrame = new javax.swing.JSplitPane();
        jScrollPaneTree = new javax.swing.JScrollPane();
        jProjectTree = new javax.swing.JTree();
        jPanel2 = new javax.swing.JPanel();
        jPanelInfo = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabelNodeName = new javax.swing.JLabel();
        jLabelNodeStartDate = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabelNodePath = new javax.swing.JLabel();
        jLabelNodeEndDate = new javax.swing.JLabel();
        jLabelNodeLeft = new javax.swing.JLabel();
        jLabelNodeRight = new javax.swing.JLabel();
        jScrollPaneTable = new javax.swing.JScrollPane();
        jTableResult = new javax.swing.JTable();
        jLabel9 = new javax.swing.JLabel();
        jLabelCurrentAction = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabelTotalRow = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        jMenuItemReloadTree = new javax.swing.JMenuItem();
        jMenuItemGetAllChild = new javax.swing.JMenuItem();
        jMenuItemGetAllDirectChild = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jScrollPaneTree.setViewportView(jProjectTree);

        jSplitPaneFrame.setLeftComponent(jScrollPaneTree);

        jPanelInfo.setBorder(javax.swing.BorderFactory.createTitledBorder("Project/Task Information"));

        jLabel2.setText("Name:");

        jLabel3.setText("Start date:");

        jLabel4.setText("End date:");

        jLabel5.setText("Left:");

        jLabel6.setText("Right:");

        jLabel8.setText("Path:");

        javax.swing.GroupLayout jPanelInfoLayout = new javax.swing.GroupLayout(jPanelInfo);
        jPanelInfo.setLayout(jPanelInfoLayout);
        jPanelInfoLayout.setHorizontalGroup(
            jPanelInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelInfoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanelInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel8, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING))
                .addGap(32, 32, 32)
                .addGroup(jPanelInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabelNodeEndDate)
                    .addComponent(jLabelNodePath, javax.swing.GroupLayout.DEFAULT_SIZE, 567, Short.MAX_VALUE)
                    .addComponent(jLabelNodeStartDate)
                    .addGroup(jPanelInfoLayout.createSequentialGroup()
                        .addComponent(jLabelNodeName, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(21, 21, 21)
                        .addGroup(jPanelInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel6, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addGap(18, 18, 18)
                        .addGroup(jPanelInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabelNodeRight)
                            .addComponent(jLabelNodeLeft))))
                .addContainerGap())
        );
        jPanelInfoLayout.setVerticalGroup(
            jPanelInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelInfoLayout.createSequentialGroup()
                .addGroup(jPanelInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanelInfoLayout.createSequentialGroup()
                        .addGroup(jPanelInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(jLabelNodeName, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanelInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(jLabelNodeStartDate))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanelInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(jLabelNodeEndDate)))
                    .addGroup(jPanelInfoLayout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel6))
                    .addGroup(jPanelInfoLayout.createSequentialGroup()
                        .addComponent(jLabelNodeLeft)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabelNodeRight)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanelInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel8)
                    .addComponent(jLabelNodePath, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jTableResult.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "id", "Name", "Start date", "End date", "Left", "Right"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Integer.class, java.lang.Integer.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jScrollPaneTable.setViewportView(jTableResult);

        jLabel9.setText("Current Action:");

        jLabel1.setText("Total row:");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPaneTable, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 708, Short.MAX_VALUE)
                    .addComponent(jPanelInfo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel9)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabelCurrentAction)
                        .addContainerGap(596, Short.MAX_VALUE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabelTotalRow)
                        .addContainerGap(631, Short.MAX_VALUE))))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jPanelInfo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabelCurrentAction, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel9, javax.swing.GroupLayout.Alignment.TRAILING))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPaneTable, javax.swing.GroupLayout.DEFAULT_SIZE, 250, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabelTotalRow)))
        );

        jSplitPaneFrame.setRightComponent(jPanel2);

        jMenu1.setText("File");

        jMenuItem1.setText("Exit");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem1);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Actions");

        jMenuItemReloadTree.setText("Reload tree");
        jMenuItemReloadTree.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemReloadTreeActionPerformed(evt);
            }
        });
        jMenu2.add(jMenuItemReloadTree);

        jMenuItemGetAllChild.setText("Get all child");
        jMenuItemGetAllChild.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemGetAllChildActionPerformed(evt);
            }
        });
        jMenu2.add(jMenuItemGetAllChild);

        jMenuItemGetAllDirectChild.setText("Get all direct child");
        jMenuItemGetAllDirectChild.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemGetAllDirectChildActionPerformed(evt);
            }
        });
        jMenu2.add(jMenuItemGetAllDirectChild);

        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jSplitPaneFrame, javax.swing.GroupLayout.PREFERRED_SIZE, 748, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jSplitPaneFrame, javax.swing.GroupLayout.DEFAULT_SIZE, 439, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jMenuItemGetAllChildActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemGetAllChildActionPerformed
        // TODO add your handling code here:                
        DefaultMutableTreeNode currentNode = getCurrentSelectionNode();
        if(currentNode == null){
            JOptionPane.showMessageDialog(null, "Please select one node to perform action");
            return;
        }
        Project prj = (Project)currentNode.getUserObject();
        ArrayList<Project> childs = prj.getAllChilds();
        updateTable(childs);
        setCurrentAction("Get all child of "+prj.toString());
    }//GEN-LAST:event_jMenuItemGetAllChildActionPerformed

    private void jMenuItemGetAllDirectChildActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemGetAllDirectChildActionPerformed
        // TODO add your handling code here:        
        DefaultMutableTreeNode currentNode = getCurrentSelectionNode();
        if(currentNode == null){
            JOptionPane.showMessageDialog(null, "Please select one node to perform action");
            return;
        }
        Project prj = (Project)currentNode.getUserObject();
        ArrayList<Project> childs = prj.getAllDirectChilds();
        updateTable(childs);
        setCurrentAction("Get all direct child of "+prj.toString());
    }//GEN-LAST:event_jMenuItemGetAllDirectChildActionPerformed

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        // TODO add your handling code here:
        System.exit(0);
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void jMenuItemReloadTreeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemReloadTreeActionPerformed
        // TODO add your handling code here:
        initTree();
    }//GEN-LAST:event_jMenuItemReloadTreeActionPerformed
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            
            public void run() {
                new GUI().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JLabel jLabelCurrentAction;
    private javax.swing.JLabel jLabelNodeEndDate;
    private javax.swing.JLabel jLabelNodeLeft;
    private javax.swing.JLabel jLabelNodeName;
    private javax.swing.JLabel jLabelNodePath;
    private javax.swing.JLabel jLabelNodeRight;
    private javax.swing.JLabel jLabelNodeStartDate;
    private javax.swing.JLabel jLabelTotalRow;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItemGetAllChild;
    private javax.swing.JMenuItem jMenuItemGetAllDirectChild;
    private javax.swing.JMenuItem jMenuItemReloadTree;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanelInfo;
    private javax.swing.JTree jProjectTree;
    private javax.swing.JScrollPane jScrollPaneTable;
    private javax.swing.JScrollPane jScrollPaneTree;
    private javax.swing.JSplitPane jSplitPaneFrame;
    private javax.swing.JTable jTableResult;
    // End of variables declaration//GEN-END:variables

    
    public void initTree() {        
        DefaultMutableTreeNode top = buildTableModelFromDB();

        /*DefaultMutableTreeNode top = new DefaultMutableTreeNode("top");
        DefaultMutableTreeNode child1 = new DefaultMutableTreeNode("child 1");
        top.add(child1);*/        
        TreeModel model = new DefaultTreeModel(top);        
        jProjectTree.setModel(model);
        
        jProjectTree.addTreeSelectionListener(new TreeSelectionListener() {            
            @Override
            public void valueChanged(TreeSelectionEvent e) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.getPath().getLastPathComponent();
                System.out.println("You selected " + node);
                //Project prj = (Project)node.getUserObject();
                updateInfoPanel();
            }
        });
        
        //jProjectTree.addTre
        
        jSplitPaneFrame.setDividerLocation(200);
        jScrollPaneTree.setViewportView(jProjectTree);        
    }
    
    public void initTable(){
        // initial table action
    }
    
    public boolean doFocusTreeNode(FocusEvent me) {
        JOptionPane.showMessageDialog(null, "Focus me");
        return true;
    }

    public boolean doFocusLostTreeNode(FocusEvent me) {
        JOptionPane.showMessageDialog(null, "Lost me");
        return true;
    }
    
    public void updateInfoPanel(){
        DefaultMutableTreeNode node = getCurrentSelectionNode();
        if(node == null){            
            return;
        }        
        Project prj = (Project)node.getUserObject();
        jLabelNodeName.setText(prj.get_name());                        
        jLabelNodeStartDate.setText(prj.get_start_date().toString());
        jLabelNodeEndDate.setText(prj.get_end_date().toString());
        jLabelNodeLeft.setText(Integer.toString(prj.get_left()));
        jLabelNodeRight.setText(Integer.toString(prj.get_right()));
        //jLabelNodePath.setText(node.getPath().toString());
        String path = "";
        ArrayList<DefaultMutableTreeNode> nodes = getCurrentSelectionPath();
        for(int i=1;i<nodes.size();i++){            
            path += "/"+nodes.get(i).getUserObject().toString();
        }
        jLabelNodePath.setText(path);
    }    
    
    public DefaultMutableTreeNode getCurrentSelectionNode(){
        TreePath path = jProjectTree.getSelectionPath();
        if(path == null){
            return null;
        }
        DefaultMutableTreeNode node = (DefaultMutableTreeNode)(path.getLastPathComponent());
        if(!(node.getUserObject() instanceof Project)){
            return null;
        }
        return node;
    }
    
    public ArrayList<DefaultMutableTreeNode> getCurrentSelectionPath(){
        Object[] path = jProjectTree.getSelectionPath().getPath();
        if(path == null){
            return null;
        }
        ArrayList<DefaultMutableTreeNode> real_path = new ArrayList<DefaultMutableTreeNode>();
        for(int i=0;i<path.length;i++){
            real_path.add((DefaultMutableTreeNode)path[i]);
        }
        return real_path;
    }
    public void updateTable(ArrayList<Project> projects){
        resetTable();
        DefaultTableModel model = (DefaultTableModel)jTableResult.getModel();       
        for(Project prj:projects){
            updateProjectInfoToTableModel(model, prj);
        }
        //jTableResult.setModel(model);
        updateTotalRow();
    }
    public void updateTotalRow(){
        jLabelTotalRow.setText(jTableResult.getRowCount()+"");
    }
    public void updateProjectInfoToTableModel(DefaultTableModel model,Project prj){
        model.addRow(new Object[]{prj.get_id(),prj.get_name(), prj.get_start_date(), prj.get_end_date(), prj.get_left(), prj.get_right()});        
    }
    public void resetTable(){
        DefaultTableModel model = (DefaultTableModel)jTableResult.getModel();
        while(model.getRowCount() > 0){
            model.removeRow(0);
        }
        //jTableResult.setModel(model);
    }
    public DefaultTableModel getTableModel(){
        DefaultTableModel model = (DefaultTableModel)jTableResult.getModel();
        return model;
    }
    
    public void setCurrentAction(String action){
        jLabelCurrentAction.setText(action);
    }        
    
    public DefaultMutableTreeNode buildTableModelFromDB(){
        ArrayList<Project> rootProjects = Project.selectRootNodes();
        DefaultMutableTreeNode top = new DefaultMutableTreeNode("Project Tree");
        for (Project prj : rootProjects) {
            DefaultMutableTreeNode nodeData = buildTableModelRecursive(prj);
            if(nodeData != null){
                top.add(nodeData);
            }
        }
        return top;
    }
    
    private DefaultMutableTreeNode buildTableModelRecursive(Project prj){        
        DefaultMutableTreeNode nodeData = new DefaultMutableTreeNode(prj);
        ArrayList<Project> childs = prj.getAllDirectChilds();
        if(!childs.isEmpty()){
            for(Project child : childs){
                DefaultMutableTreeNode childModel = buildTableModelRecursive(child);                
                nodeData.add(childModel);
            }
        }
        //root.add(nodeData);
        return nodeData;
    }
}
